package key_pair

import (
	"code.gitea.io/gitea/modules/setting"
	Result "code.gitea.io/gitea/routers/entity"
	gitea_web_context "code.gitea.io/gitea/services/context"
	"code.gitea.io/gitea/services/devstar_ssh_key_pair/api_service"
	"strconv"
)

// GenerateNewSSHSessionKeyPair 创建临时会话 SSH 密钥对
// GET /api/devstar_ssh/key_pair/new_temp
func GenerateNewSSHSessionKeyPair(ctx *gitea_web_context.Context) {

	// 1. 节约服务器资源：仅限已登录用户使用生成临时 SSH 会话密钥对
	if ctx == nil || ctx.Doer == nil {
		Result.RespUnauthorizedFailure.RespondJson2HttpResponseWriter(ctx.Resp)
		return
	}

	// 2. 调用 API Service 层，生成 SSH 私钥、公钥、公钥指纹
	err, vo := api_service.GenerateNewRSASSHSessionKeyPair()
	if err != nil {
		resp := Result.ResultType{
			Code: Result.RespSSHKeyPairGenFailed.Code,
			Msg:  Result.RespSSHKeyPairGenFailed.Msg,
			Data: map[string]string{
				"ErrorMsg": err.Error(),
				"KeySize":  strconv.Itoa(setting.Devstar.SSHKeypair.KeySize),
			},
		}
		resp.RespondJson2HttpResponseWriter(ctx.Resp)
		return
	}

	resp := Result.ResultType{
		Code: Result.RespSuccess.Code,
		Msg:  Result.RespSuccess.Msg,
		Data: map[string]string{
			"publicKeyPem":  vo.PublicKeyPEM,
			"privateKeyPem": vo.PrivateKeyPEM,
			"publicKeySsh":  vo.PublicKeySsh,
			"KeySize":       vo.KeySize,
		},
	}
	resp.RespondJson2HttpResponseWriter(ctx.Resp)
	return
}
